#include "client/Configuration.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <unistd.h>

using std::cout;
using std::ifstream;
using std::istringstream;
using std::pair;
using std::cerr;

Configuration *Configuration::_instance = nullptr;

Configuration *Configuration::getInstance(const string &filepath)
{
    if(_instance)return _instance;
    _instance = new Configuration(filepath);
    return _instance;
}

Configuration::~Configuration(){}

void Configuration::initConfiguration(){
    getConfigMap();
    //_stopWordList = getStopWordList();
}

Configuration::Configuration(const string &filepath):_filepath(filepath){}

map<string, string> &Configuration::getConfigMap(){
    //打开配置文件
    ifstream ifs_conf;
    string conf_path = _filepath + "/conf/conf_list.conf";
    ifs_conf.open(conf_path);

    //读取配置文件
    string item;
    char line[256];
    pair<string, set<string>> conf_pair;
    cout << "start get config" << '\n';
    while(ifs_conf.getline(line, 256)){
        bool left = true;
        bool is_exist = false;
        istringstream iss(line);
        while(iss >> item){
            if(item == "=")continue;
            if(left){
                conf_pair.first = item;
                left = false;
                if (_configMap.find(conf_pair.first) != _configMap.end())is_exist = true;
            }else{
                conf_pair.second.insert(_filepath + item);
            }
        }

        if(is_exist){
            _configMap.find(conf_pair.first)->second.insert(*(conf_pair.second.begin()));
        }
        _configMap.insert(conf_pair);
        conf_pair.second.clear();
    } 

    // //测试打印
    // int kk = 1;
    // for(auto & i: _configMap){
    //     cout << kk << ' ';
    //     kk++;
    //     for(auto &j : i.second){
    //         cout << i.first << " " << j << '\n';
    //     }
    // }

}

set<string> Configuration::getStopWordList(){
    //获取停用词路径
    ifstream ifs_stop;
    auto it = _configMap.find("stop_words_cn");
    const set<string> &file_list = it->second;

    // 获取停词
    string word;
    set<string> stop_word;
    for(auto &i : file_list){
        ifs_stop.open(i);
        while (ifs_stop >> word)
            stop_word.insert(word);
    }
    return stop_word;
}

set<string> &Configuration::find_config(const string &key){
    return _configMap.find(key)->second;
}